// pages/occupancy/occupancy.js
const app = getApp()
var host = app.globalData.host;
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({ key: 'MBUBZ-VY2CW-4B5RA-OOIFR-U7L63-4VF6G' });

Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    imgList: [],
    imgListLogo:[],
    picker: [],
    classIndex: 0,
    classList: [],
    edit:false,
    list:[],
    isSubBtn: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      edit:options.edit
    })
    var id = options.id;
    wx.request({
      url: host + 'enterprise/getgroup',
      data: {
        uid:wx.getStorageSync("uid"),
        id:id,
        edit: options.edit
      },
      success: function (res) {
        var picker = [];
        var groupList = res.data.data.group;
        if (that.data.edit == "true"){
          var arr = res.data.data.list.tags.split(',');
          var location = res.data.data.list.location.split(",");
          that.setData({
            list:res.data.data.list,
            classList: arr,
            imgList: res.data.data.list.images,
            imgListLogo:res.data.data.list.logo,
            address: res.data.data.list.address,
            latitude: location[0],
            longitude: location[1]
          })
        }
        for(var i=0; i<groupList.length; i++){
          picker[i] = groupList[i].title
        }
        that.setData({
          groupList: groupList,
          picker: picker
        })
        
      }
    })
  },
  onShow(){
    var that = this;
  },
  openMap: function () {
    var that  = this;
    wx.chooseLocation({
      success:function(res){
        that.setData({
          address:res.address,
          latitude: res.latitude,
          longitude: res.longitude
        })
      },
      fail:function(){
        
      }
    })
  },
  PickerChange(e) {
    console.log(e);
    var index = e.detail.value;
    this.setData({
      index: e.detail.value,
      pickerT: this.data.picker[index]
    })
  },
  ChooseImageLogo() {
    var that = this;
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        var tempFilePath=res.tempFilePaths;
        wx.showLoading({  title: '图片审核中。。。', })
        //获取图片的临时路径
        const tempFilePaths = res.tempFilePaths[0]
        //使用getFileSystemManager获取图片的Buffer流
        wx.getFileSystemManager().readFile({
          filePath: tempFilePaths,                   
          success: (res)=>{ 
            const buffer = res.data
            //调用云函数进行审核
            wx.cloud.callFunction({
              name: 'checkImg',              
              data:{ 'buffer': buffer }            
            }).then(res=>{
              wx.hideLoading();
              console.log("checkImg:"+res);   
              //存在违规
              if(res.result.errCode != 0){
                wx.showModal({ title: '违规提示',  content: '图片违规', showCancel: false, confirmColor: '#DC143C'
                })
              }else{
                if (that.data.imgListLogo.length != 0) {
                  that.setData({
                    imgListLogo: that.data.imgListLogo.concat(tempFilePath)
                  })
                } else {
                  that.setData({
                    imgListLogo: tempFilePath
                  })
                }
              }
            })
          }
        })
      }
    });
  },

  ChooseImage() {
    var that  = this;
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
       
        var tempFilePath=res.tempFilePaths;
        console.log("chooseImage that:"+that);
        wx.showLoading({
          title: '图片审核中。。。',
        })
        //获取图片的临时路径
        var tempFilePathss = res.tempFilePaths.join(',');
        const tempFilePaths = res.tempFilePaths[0]
        //使用getFileSystemManager获取图片的Buffer流
        wx.getFileSystemManager().readFile({
          filePath: tempFilePaths,                   
          success: (res)=>{ 
            const buffer = res.data
            //调用云函数进行审核
            wx.cloud.callFunction({
              name: 'checkImg',              
              data:{
                'buffer': buffer
              }            
            }).then(res=>{
              wx.hideLoading();
              console.log("checkImg:"+res);   
              //存在违规
              if(res.result.errCode != 0){
                wx.showModal({
                  title: '违规提示',
                  content: '图片违规',
                  showCancel: false,
                  confirmColor: '#DC143C'
                })
              }else{
                wx.uploadFile({
                  url: host + 'enterprise/addimgs',
                  filePath: tempFilePathss,
                  name: 'image',
                  header: {
                    "Content-Type": "multipart/form-data"
                  },
                  success: function (ress) {
                    var data = ress.data.split(',');
                    if (that.data.imgList.length != 0) {
                      that.setData({
                        imgList: that.data.imgList.concat(data)
                      })
                    } else {
                      that.setData({
                        imgList: data
                      })
                    }
                  },
                })
              }
            })
          }
        })  
          
      }

    });
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  ViewImageLogo(e) {
    wx.previewImage({
      urls: this.data.imgListLogo,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '召唤师',
      content: '确定要删除这段回忆吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  DelImgLogo(e) {
    wx.showModal({
      title: '召唤师',
      content: '确定要删除这段回忆吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          this.data.imgListLogo.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgListLogo: this.data.imgListLogo
          })
        }
      }
    })
  },
  clickClass: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    that.setData({
      classIndex: index
    })
  },
  fromSubmitCheck:function(e){
    var that = this;

    // 判断logo和轮播图
    var imgList = that.data.imgList;
    var imgListLogo = that.data.imgListLogo;
    if (imgListLogo.length == 0){
      wx.showToast({
        title: '请上传企业LOGO',
        icon: 'none'
      })
      return false;
    }
    if (imgList.length == 0) {
      wx.showToast({
        title: '请上传企业企业轮播图',
        icon: 'none'
      })
      return false;
    }

var txtStr="";
txtStr+=e.detail.value.name;//企业名称
txtStr+=e.detail.value.announcement;//企业公告
txtStr+=e.detail.value.user;//联系人：
txtStr+=e.detail.value.position;//职位
txtStr+=e.detail.value.city;//城市
txtStr+=e.detail.value.descinfo;//企业介绍
    wx.cloud.callFunction({
      config:{ env: 'public-bb1cff'},
      name: 'checkStr',
      data: {
        txt: txtStr
      },
      success(res) {
        console.log('ContentCheck-res',res)
        if (res.result.errCode == 87014) {
          console.log(res.errCode)
          wx.showToast({  icon: 'none',    title: '填写内容有违规信息', });
          return false;
        }else{
          console.log('合法');
          that.formSubmit(e);
        }
      },fail(err){
        wx.showToast({  icon: 'none',   title: '填写内容有违规信息',
        });
        return false;
      }
    })
  },
  formSubmit: function (e) {
    var that = this;

    // 判断logo和轮播图
    var imgList = that.data.imgList;
    var imgListLogo = that.data.imgListLogo;
    if (imgListLogo.length == 0){
      wx.showToast({
        title: '请上传企业LOGO',
        icon: 'none'
      })
      return false;
    }
    if (imgList.length == 0) {
      wx.showToast({
        title: '请上传企业企业轮播图',
        icon: 'none'
      })
      return false;
    }

    var postData = {};
    postData.name = e.detail.value.name;
    postData.group_id = that.data.groupList[that.data.index].id;
    postData.address = that.data.address;
    postData.location = that.data.latitude + ',' + that.data.longitude;
    postData.tags = that.data.classList.join(',');
    postData.images = that.data.imgList.join(',');
    postData.notice = e.detail.value.announcement;
    postData.contacts = e.detail.value.user;
    postData.position = e.detail.value.position;
    postData.mobile = e.detail.value.phone;
    postData.city = e.detail.value.city;
    postData.about_us = e.detail.value.descinfo;
    if (postData.name && postData.group_id && postData.address && postData.location && postData.notice && postData.contacts && postData.position && postData.mobile && postData.city && postData.about_us){
      var edit = that.data.edit;
      if(edit == "true"){
        var url = host + 'enterprise/edit';
        var id = e.target.dataset.id;
      }else{
        var url = host + 'enterprise/add';
        var id = 0;
      }
      
      this.setData({
        isSubBtn: true
      })
      wx.request({
        url: url,
        data: {
          uid: wx.getStorageSync('uid'),
          pramst: postData,
          id:id
        },
        success: function(res){
          if(res.data.code == 1){
            var id = res.data.data;
            // for (var i = 0; i < imgList.length; i++) {
            //   wx.uploadFile({
            //     url: host + 'enterprise/addimgs?id=' + id,
            //     filePath: imgList[i],
            //     name: 'image',
            //     header: {
            //       "Content-Type": "multipart/form-data"
            //     },
            //     success: function (ress) {

            //     },
            //   })
            // }
            wx.uploadFile({
              url: host + 'enterprise/addlogoimgs?id=' + id,
              filePath: imgListLogo[0],
              name: 'image',
              header: {
                "Content-Type": "multipart/form-data"
              },
              success: function (ress) {

              },
            })
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000,
              success: function () {
                setTimeout(function () {
                  wx.navigateBack({
                    delta: 1
                  })
                }, 2000);
              }
            })
          }
        },
        fail: function (res) {
          this.setData({
            isSubBtn: false
          })
        }
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '请填写完整的信息',
        showCancel: false
      })
    }
  },

  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value
    })
  },
  clear(e) {
    console.log(e)
    var index = e.currentTarget.dataset.index;
    this.data.classList.splice(index, 1);
    this.setData({
      classList: this.data.classList
    })
  },
  hideModalQd(e) {
    var classList = this.data.classList;
    if (this.data.region == null) {
      wx.showModal({
        title: '不可以为空',
      })
    } else {
      classList.push(this.data.region)
    }
    this.setData({
      modalName: null,
      classList: classList
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
})